package com.zfsbs.activity;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.model.SbsPrinterData;
import com.tool.utils.activityManager.AppManager;
import com.tool.utils.utils.ALog;
import com.tool.utils.utils.FyAidlUtils;
import com.tool.utils.utils.LogUtils;
import com.tool.utils.utils.SPUtils;
import com.tool.utils.utils.StringUtils;
import com.tool.utils.utils.ToastUtils;
import com.tool.utils.utils.ToolNewLand;
import com.zfsbs.R;
import com.zfsbs.common.CommonFunc;
import com.zfsbs.config.Config;
import com.zfsbs.config.Constants;
import com.zfsbs.core.action.FyPrintUtils;
import com.zfsbs.core.myinterface.ActionCallbackListener;
import com.zfsbs.model.SmFyResponse;
import com.zfsbs.model.SmResponse;
import com.zfsbs.model.TransUploadRequest;
import com.zfsbs.myapplication.MyApplication;

import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;

import java.util.List;

public class SaleUndoActivity extends BaseActivity implements OnClickListener {

    private LinearLayout llPassword;
    private LinearLayout llTraceNo;
    private LinearLayout llText;
    private EditText etPassword;
    private EditText etTraceNo;
    private Button btnPassword;
    private Button btnTraceNo;
    private Button btnInfo;
    private Button btnClose;
    private TextView tv;

    private List<SbsPrinterData> allData;
    private int index;
    private String orderNo;

    private int app_type = 0;
    private String phone;
    private int points = 0;
    private boolean isMember;
//    private String oldOrderId = "";
    private String orderId;
    private String amt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mContext = this;
        setContentView(R.layout.activity_sale_undo);
//        AppManager.getAppManager().addActivity(this);
        initTitle("消费撤销");
        initView();
        addListener();
    }

    private void initView() {
        etPassword = (EditText) findViewById(R.id.id_input_password);
        etTraceNo = (EditText) findViewById(R.id.id_input_trace_no);
        btnPassword = (Button) findViewById(R.id.id_password_sure);
        btnTraceNo = (Button) findViewById(R.id.id_traceNO_sure);
        btnInfo = (Button) findViewById(R.id.id_info_sure);
        btnClose = (Button) findViewById(R.id.id_close);

        llPassword = (LinearLayout) findViewById(R.id.id_ll_MasterId);
        llTraceNo = (LinearLayout) findViewById(R.id.id_ll_trace_no);
        llText = (LinearLayout) findViewById(R.id.id_ll_text);

        tv = (TextView) findViewById(R.id.id_tv);

    }

    private void addListener() {
        btnPassword.setOnClickListener(this);
        btnTraceNo.setOnClickListener(this);
        btnInfo.setOnClickListener(this);
        btnClose.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.id_password_sure:
                isCheckPassword();
                break;
            case R.id.id_traceNO_sure:
                isCheckTraceNo();
                break;
            case R.id.id_info_sure:
                SaleUndoAction();
                break;
            case R.id.id_close:
                finish();
                break;
            default:
                break;
        }
    }

    private void SaleUndoAction() {
        String traceNo = StringUtils.removeBlank(etTraceNo.getText().toString(), ' ');
        LogUtils.e(traceNo + "");
//        CommonFunc.undo(this, 0, "200000", "", orderId, traceNo);

        Intent intent8 = new Intent();
        intent8.setComponent(new ComponentName("com.fuyousf.android.fuious","com.fuyousf.android.fuious.MainActivity"));
        //包名     包名+类名（全路径）
        intent8.putExtra("transName", "消费撤销");
        intent8.putExtra("amount", amt);
        intent8.putExtra("oldTrace", traceNo);
        intent8.putExtra("isManagePwd", "false");
        intent8.putExtra("orderNumber",  orderId);
        intent8.putExtra("version", "1.0.7");


        startActivityForResult(intent8, 1);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && data != null) {

//            switch (resultCode) {
//                case Activity.RESULT_OK:
//
//                    LogUtils.e("msg_tp:" + data.getStringExtra("msg_tp") + "\n" +
//                            "pay_tp:" + data.getStringExtra("pay_tp") + "\n" +
//                            "proc_tp:" + data.getStringExtra("proc_tp") + "\n" +
//                            "proc_cd:" + data.getStringExtra("proc_cd") + "\n" +
//                            "amt:" + data.getStringExtra("amt") + "\n" +
//                            "systraceno:" + data.getStringExtra("systraceno") + "\n" +
//                            "sysoldtraceno:" + data.getStringExtra("sysoldtraceno") + "\n" +
//                            "order_no:" + data.getStringExtra("order_no") + "\n" +
//                            "appid:" + data.getStringExtra("appid") + "\n" +
//                            "time_stamp:" + data.getStringExtra("time_stamp") + "\n" +
//                            "print_info:" + data.getStringExtra("print_info") + "\n" +
//                            "batchbillno:" + data.getStringExtra("batchbillno") + "\n" +
//                            "merid:" + data.getStringExtra("merid") + "\n" +
//                            "termid:" + data.getStringExtra("termid") + "\n");
//
//
//                    ALog.json("txndetail", data.getExtras().getString("txndetail"));
//
//                    String payType = data.getStringExtra("pay_tp");
//                    String detail = data.getExtras().getString("txndetail");
//
//                    if ("0".equals(payType)) { //银行卡
//                        setUndo(detail);
//                        setTransCancel();
//                    }
//
//                    break;
//                case Activity.RESULT_CANCELED:
//                    ToastUtils.CustomShow(mContext, data.getStringExtra("reason"));
//                    break;
//                case -2:
//                    ToastUtils.CustomShow(mContext, data.getStringExtra("reason"));
//                    break;
//                default:
//                    break;
//            }

            switch (resultCode) {
                case Activity.RESULT_CANCELED:
                    String reason = "";
                    String traceNo = "";
                    String batchNo = "";
                    String ordernumber = "";
                    if (data != null) {
                        Bundle b = data.getExtras();
                        if (b != null) {
                            reason = (String) b.get("reason");
                            traceNo = (String) b.getString("traceNo");
                            batchNo = (String) b.getString("batchNo");
                            ordernumber = (String) b.getString("ordernumber");
                        }
                    }
                    if (reason != null) {
                        Log.d("reason", reason);
                        Toast.makeText(this, reason, Toast.LENGTH_SHORT).show();
                    }
                    Log.e("TAG", "失败返回值--reason--返回值：" + reason + "/n 凭证号：" + traceNo + "/n 批次号：" + batchNo + "/n 订单号：" + ordernumber);

                    break;
                case Activity.RESULT_OK:
                    String print = data.getStringExtra("reason");//打印成功返回数据
                    Log.e("TAG", "成功返回值--reason--返回值：" + print);

                    String b = data.getStringExtra("batchNo");//批次号
                    String c = data.getStringExtra("traceNo");//流水号
                    String d = data.getStringExtra("cardNo");//卡号

                    String e = data.getStringExtra("merchantId");//商户号
                    String f = data.getStringExtra("terminalId");//终端号

                    String g = data.getStringExtra("referenceNo");//参考号
                    String h = data.getStringExtra("issue");//发卡行
                    String i = data.getStringExtra("type");//卡类型
                    String j = data.getStringExtra("date");//日期
                    String k = data.getStringExtra("time");//时间

                    String l = data.getStringExtra("wireless.apn");//apn
                    String m = data.getStringExtra("wireless.username");//用户名
                    String n = data.getStringExtra("wireless.password");//密码
                    String o = data.getStringExtra("wireless.apnEnabled");//Apn是否开启
                    String p = data.getStringExtra("merchantName");//商户名

                    String r = data.getStringExtra("oldReferenceNo");//原参考号

                    String t = data.getStringExtra("orderNumber");
                    String tzfb = data.getStringExtra("zfbOrderNumber");
                    String twx = data.getStringExtra("wxOrderNumber");

                    String u = data.getStringExtra("oldOrderNumber");
                    String sWx = data.getStringExtra("wxOldOrderNumber");
                    String sZfb = data.getStringExtra("zfbOldOrderNumber");

                    String wMb = data.getStringExtra("zfbMbOldOrderNumber");
                    String zMb = data.getStringExtra("wxMbOldOrderNumber");

                    String tui = data.getStringExtra("tuiOldOrderNumber");

                    String settleData = data.getStringExtra("settleJson");
                    String json = data.getStringExtra("json");

                    String return_Code = data.getStringExtra("return_txt");//扫码返回数据

                    String authorizationCode = data.getStringExtra("authorizationCode");//预授权 授权码

                    String backOldReferenceNo = data.getStringExtra("backOldReferenceNo");//退货的原参考号

                    String referenceNoSuccess = data.getStringExtra("referenceNoSuccess");//订单查询返回参考号

                    String oldReferenceNoSuccess = data.getStringExtra("oldReferenceNoSuccess");//订单查询返回原参考号

                    String amount = data.getStringExtra("amount");//金额

                    String acqId = data.getStringExtra("acqId");//收单行

                    String expiredDate = data.getStringExtra("expiredDate");//卡有效期

                    String transactionType = data.getStringExtra("transactionType"); //交易类型

                    JSONObject jsO = new JSONObject();
                    try {
                        jsO.put("reason", print);
                        jsO.put("batchNo", b);//批次号
                        jsO.put("traceNo", c);//流水号
                        jsO.put("cardNo", d);//卡号
                        jsO.put("merchantId", e);//商户号
                        jsO.put("terminalId", f);//终端号
                        jsO.put("referenceNo", g);//参考号
                        jsO.put("issue", h);//发卡行
                        jsO.put("type", i);//卡类型
                        jsO.put("date", j);//日期
                        jsO.put("time", k);//时间
                        jsO.put("wireless.apn", l);//apn
                        jsO.put("wireless.username", m);//用户名
                        jsO.put("wireless.password", n);//密码
                        jsO.put("wireless.apnEnabled", o);//Apn是否开启
                        jsO.put("merchantName", p);//商户名
                        jsO.put("oldReferenceNo", r);//原参考号
                        jsO.put("backOldReferenceNo", backOldReferenceNo);//退货原参考号
                        jsO.put("orderNumber", t);//消费订单号
                        jsO.put("zfbOrderNumber", tzfb);//支付宝消费订单号
                        jsO.put("wxOrderNumber", twx);//微信消费订单号
                        jsO.put("oldOrderNumber", u);//原消费订单号
                        jsO.put("wxOldOrderNumber", sWx);//原支付宝消费订单号
                        jsO.put("zfbOldOrderNumber", sZfb);//原微信消费订单号
                        jsO.put("zfbMbOldOrderNumber", wMb);//原支付宝末笔订单号
                        jsO.put("wxMbOldOrderNumber", zMb);//原微信末笔订单号
                        jsO.put("tuiOldOrderNumber", tui);//退款订单号
                        jsO.put("return_txt", return_Code);//扫码返回数据
                        jsO.put("authorizationCode", authorizationCode);//授权码
                        jsO.put("referenceNoSuccess", referenceNoSuccess);//订单查询参考号
                        jsO.put("oldReferenceNoSuccess", oldReferenceNoSuccess);//订单查询原参考号
                        jsO.put("amount", amount);
                        jsO.put("acqId", acqId);
                        jsO.put("expiredDate", expiredDate);
                        jsO.put("settleJson", settleData);
                        jsO.put("json", json);
                        jsO.put("transactionType", transactionType);

                    } catch (JSONException e1) {
                        e1.printStackTrace();
                    }


                    ALog.json(jsO.toString());


                    setUndo(jsO.toString());
                    setTransCancel();


//                    if (requestCode == Constants.PAY_WAY_FLOT){
//                        setFlot(jsO.toString());
//                    }else if (requestCode == Constants.PAY_WAY_ALY){
//                        setSmPay(jsO.toString(), Constants.PAY_WAY_ALY);
//                    }else if (requestCode == Constants.PAY_WAY_WX){
//                        setSmPay(jsO.toString(), Constants.PAY_WAY_WX);
//                    }else if (requestCode == 99){
//                        Gson gson = new Gson();
//                        TransUploadRequest request = gson.fromJson(printerData.getTransUploadData(), TransUploadRequest.class);
//                        ALog.json(request.toString());
//                        getPrinterData(request);
//                    }


                    break;
            }


        }
    }

    private void setUndo(String data){

        Gson gson = new Gson();
        SmFyResponse smResponse = gson.fromJson(data, SmFyResponse.class);


        printerData.setMerchantName(smResponse.getMerchantName());
        printerData.setMerchantNo(smResponse.getMerchantId());
        printerData.setTerminalId(smResponse.getTerminalId());
        printerData.setOperatorNo((String) SPUtils.get(this, Constants.USER_NAME, ""));
//        printerData.setAcquirer(smResponse.getAcqno());
        printerData.setIssuer(smResponse.getIssue());
        printerData.setCardNo(smResponse.getCardNo());
        printerData.setTransType(2 + "");
//        printerData.setExpDate(smResponse.getExpdate());
        printerData.setBatchNO(smResponse.getBatchNo());
        printerData.setVoucherNo(smResponse.getTraceNo());
        printerData.setDateTime(
                StringUtils.formatTime(StringUtils.getCurYear()+smResponse.getDate()+smResponse.getTime()));
//        printerData.setAuthNo(smResponse.getAuthcode());
//        LogUtils.e(smResponse.getRefernumber());
        printerData.setReferNo(smResponse.getReferenceNo());
        printerData.setPointCoverMoney(0);
        printerData.setCouponCoverMoney(0);
        printerData.setOrderAmount((int)Long.parseLong(smResponse.getAmount()));
        printerData.setAmount(StringUtils.formatIntMoney(Long.parseLong(smResponse.getAmount())));
        printerData.setPayType(Constants.PAY_WAY_UNDO);
    }



    private void setTransUpLoadData(TransUploadRequest request) {
        Gson gson = new Gson();
        String data = gson.toJson(request);
        LogUtils.e("SaleUndoActivity", data);
        printerData.setTransUploadData(data);
    }


    /**
     * 撤销流水上送
     */
    private void setTransCancel() {
        final TransUploadRequest request = new TransUploadRequest();

        printerData.setClientOrderNo(orderId);
        printerData.setOldOrderId(orderNo);
        request.setSid(MyApplication.getInstance().getLoginData().getSid());
        request.setAction("2");
        request.setOld_trade_order_num(orderNo);
        request.setNew_trade_order_num(orderId);
        request.setPayType(Constants.PAY_WAY_UNDO);
        request.setAuthCode(printerData.getVoucherNo());
        request.setClientOrderNo(orderId);
        request.setT(StringUtils.getdate2TimeStamp(printerData.getDateTime()));

        this.sbsAction.transCancelRefund(this, request, new ActionCallbackListener<String>() {
            @Override
            public void onSuccess(String data) {
                ToastUtils.CustomShow(SaleUndoActivity.this, "撤销成功");
                printerData.setRefundUpload(true);
                //这个地方用来 在交易记录里去打印用的
                request.setSid(MyApplication.getInstance().getLoginData().getSid());
                // 备份下交易流水数据
                setTransUpLoadData(request);
                printerData.setApp_type(app_type);



                PrinterDataSave();
                    // 打印
//                    Printer.print(printerData, SaleUndoActivity.this);
//                ToolNewLand.getToolNewLand().printText(printerData);
                print(mContext,printerData);
                finish();

            }

            @Override
            public void onFailure(String errorEvent, String message) {
                ToastUtils.CustomShow(SaleUndoActivity.this, "撤销成功");
                // 备份下交易流水数据
                request.setSid(MyApplication.getInstance().getLoginData().getSid());
                setTransUpLoadData(request);
                // 保存打印的数据，不保存图片数据
                printerData.setApp_type(app_type);
                PrinterDataSave();
                // 打印
//                Printer.print(printerData, SaleUndoActivity.this);
//                ToolNewLand.getToolNewLand().printText(printerData);
                print(mContext,printerData);
                finish();
            }

            @Override
            public void onFailurTimeOut(String s, String error_msg) {

            }

            @Override
            public void onLogin() {

            }
        },true);
    }



    private void print(Context context, SbsPrinterData data){
        if (FyAidlUtils.getPrintService() != null){
            String jsonDate = FyPrintUtils.printText(context, data);
            Log.e("TAG", "json："+jsonDate);
            if (StringUtils.isBlank(jsonDate)){
                return;
            }
            try {
                FyAidlUtils.getPrintService().print(jsonDate);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }



    private Handler mhandler = new Handler() {
        public void handleMessage(Message msg) {
            Bundle bundle = msg.getData();
            Bitmap point_bitmap = bundle.getParcelable("point_bitmap");
            Bitmap title_bitmap = bundle.getParcelable("title_bitmap");
            printerData.setPoint_bitmap(point_bitmap);
            printerData.setCoupon_bitmap(title_bitmap);


            // 打印
//            Printer.print(printerData, SaleUndoActivity.this);
//            ToolNewLand.getToolNewLand().printText(printerData);
            print(mContext,printerData);
            finish();
        }

        ;
    };



    private void PrinterDataSave() {

        CommonFunc.PrinterDataDelete();
        printerData.setStatus(true);
        if (printerData.save()) {
            LogUtils.e("打印数据存储成功");
        } else {
            LogUtils.e("打印数据存储失败");
        }
    }

    private void isCheckTraceNo() {
        if (StringUtils.isEmpty(etTraceNo.getText().toString())) {
            ToastUtils.CustomShow(this, "请输入原交易凭证号");
            return;
        }
        saleUndoInfo();
    }

    private void saleUndoInfo() {

        // 从交易记录中读取数据
        allData = DataSupport.order("id desc").limit(100).find(SbsPrinterData.class);
        if (allData.size() <= 0) {
            ToastUtils.CustomShow(this, "没有交易记录");
            return;
        }


        // 遍历
        for (int i = 0; i < allData.size(); i++) {
            // 遍历刷卡支付
            if (allData.get(i).getPayType() == Constants.PAY_WAY_FLOT && !StringUtils.isEmpty(allData.get(i).getVoucherNo())) {
                if (StringUtils.isEquals(allData.get(i).getVoucherNo(), etTraceNo.getText().toString())) {
                    showTransInfo(allData.get(i));
                    index = i;
                    return;
                }
            }
        }
        ToastUtils.CustomShow(this, "没有该笔交易");

    }

    private void showTransInfo(SbsPrinterData sbsPrinterData) {
//        llTraceNo.setVisibility(View.GONE);
//        llText.setVisibility(View.VISIBLE);
//        String str = "卡号：\r\n" + sbsPrinterData.getCardNo() + "\r\n" + "金额：" + sbsPrinterData.getAmount() + "\r\n"
//                + "交易时间：\r\n" + sbsPrinterData.getDateTime();
//        tv.setText(str);

        //获取交易的订单号
        Gson gson = new Gson();
        TransUploadRequest data = gson.fromJson(sbsPrinterData.getTransUploadData(), TransUploadRequest.class);

        if (data != null) {
//            orderNo = data.getClientOrderNo();
            orderNo = data.getOld_trade_order_num();
        }

//        oldOrderId = sbsPrinterData.getClientOrderNo();
        orderId = CommonFunc.getNewClientSn(mContext);
        app_type=sbsPrinterData.getApp_type();
        phone=sbsPrinterData.getPhoneNo();
        points = sbsPrinterData.getPoint();
        isMember = sbsPrinterData.isMember();
        amt = StringUtils.fillZero(sbsPrinterData.getAmount(), 12);

        SaleUndoAction();
    }

    private void isCheckPassword() {
        String pass = (String) SPUtils.get(this, Constants.MASTER_PASS, Constants.DEFAULT_MASTER_PASS);
        if (StringUtils.isEmpty(etPassword.getText().toString())) {
            ToastUtils.CustomShow(this, "请输入主管理密码");
            return;
        }
        if (!StringUtils.isEquals(pass, etPassword.getText().toString())) {
            ToastUtils.CustomShow(this, "主管理密码错误");
            return;
        }
        llPassword.setVisibility(View.GONE);
        llTraceNo.setVisibility(View.VISIBLE);
        etTraceNo.setFocusable(true);
        etTraceNo.requestFocus();
    }
}
